/**
  Generated Main Source File

  Company:
    Microchip Technology Inc.

  File Name:
    main.c

  Summary:
    This is the main file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs

  Description:
    This header file provides implementations for driver APIs for all modules selected in the GUI.
    Generation Information :
        Product Revision  :  PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.65.2
        Device            :  PIC18LF46K22
        Driver Version    :  2.00
*/

/*
    (c) 2018 Microchip Technology Inc. and its subsidiaries. 
    
    Subject to your compliance with these terms, you may use Microchip software and any 
    derivatives exclusively with Microchip products. It is your responsibility to comply with third party 
    license terms applicable to your use of third party software (including open source software) that 
    may accompany Microchip software.
    
    THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER 
    EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY 
    IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS 
    FOR A PARTICULAR PURPOSE.
    
    IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, 
    INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND 
    WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP 
    HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO 
    THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL 
    CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT 
    OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS 
    SOFTWARE.
*/

//#define FCY     16000000UL 

#include "mcc_generated_files/mcc.h"
#include "stdio.h"
#include "string.h"

void hexToChar(uint8_t * value, uint8_t * str, int lens) ;

#if 0   //rn2903_1
uint8_t nwkSKey[16] = {0x05,0x60,0x6C,0x0E,0x0D,0xC7,0xF1,0x2F,0x86,0x74,0x09,0x60,0xC8,0xBA,0x63,0xAA};
uint8_t appSKey[16] = {0x76,0x4A,0x4E,0xB6,0x5F,0x2B,0x0E,0xDA,0xE3,0x86,0xD9,0x4E,0x3A,0x0C,0x83,0xDA};
uint32_t devAddr = 0x26011655;
#endif


#if 0   //rn2903_2
uint8_t nwkSKey[16] = { 0xAE, 0xE2, 0xFA, 0x33, 0x3C, 0x2B, 0x20, 0xB5, 0xCB, 0xB1, 0xC3, 0x20, 0xBB, 0xC5, 0x78, 0xEA };
uint8_t appSKey[16] = { 0xB0, 0x5A, 0xC1, 0xE6, 0xC7, 0xAF, 0x30, 0xD2, 0x66, 0x5F, 0x16, 0x64, 0xE4, 0x00, 0x2E, 0x84 };
uint32_t devAddr = 0x26011AB5;
#endif

#if 1   //rn2903_3
uint8_t nwkSKey[16] = { 0x71, 0x4A, 0x07, 0xB8, 0x95, 0x63, 0xF8, 0x01, 0x75, 0xC0, 0x6A, 0xBE, 0xAC, 0x76, 0xD2, 0x4F };
uint8_t appSKey[16] = { 0x7E, 0x2E, 0xA4, 0xA9, 0x89, 0x9B, 0x41, 0x6C, 0xB2, 0x4E, 0xDC, 0x17, 0xB0, 0x4D, 0x38, 0x1D }; 
uint32_t devAddr = 0x26011CC9;
#endif

/*
uint8_t DevEui[8] = {0x8B, 0x7F, 0x20, 0x00, 0x0B, 0xA3, 0x04, 0x00};
uint8_t AppKey[16] = {0x8B, 0xAC, 0xA6, 0xB4, 0x1E, 0x73, 0x16, 0x31, 0x1D,
0x6C, 0x60, 0xFE, 0x4A, 0x40, 0x80, 0x6D};
uint8_t AppEui[8] = {0x63, 0x8E, 0x00, 0xD0, 0x7E, 0xD5, 0xB3, 0x70};

*/

#if 0
uint8_t DevEui[8] = {0x00, 0x04, 0xA3, 0x0B, 0x00, 0x20, 0x7F, 0x8B};
uint8_t AppKey[16] = {0x6D, 0x80, 0x40, 0x4A, 0xFE, 0x60, 0x6C, 0x1D, 0x31,
0x16, 0x73, 0x1E, 0xBA, 0xA6, 0xAC, 0x8B};
uint8_t AppEui[8] = {0x70, 0xB3, 0xD5, 0x7E, 0xD0, 0x00, 0x8E, 0x63};
#endif


uint32_t freqUsed;

/*
int putch( int c ) 
{
	EUSART1_Write(c);
	return c;
}
*/
char rec_buf[32];

void RxData(uint8_t* pData, uint8_t dataLength, OpStatus_t status)
{
    uint16_t i;
        printf("get data:");
        for(i = 0;i< dataLength; i++)
            printf("%x ", pData[i]);
       // printf("rssi 0x:%x", RADIO_ReadRandom ());
        printf("\r\n");
}

void RxJoinResponse(bool status)
{
  //  if(status != 0)
  //  LORAWAN_SetUplinkCounter(0);
}
bit sw_b;
volatile uint32_t sw_count=0, sw_count_old=0;
volatile uint8_t lora_send_data[8];

uint8_t eui_v[8];
uint8_t send_string_buf[32];
uint16_t ping_data_count=0;

void timer_handle_for_ping_data()  //inteval is 10ms, 3000 mean 5minutes, 
{
    if(ping_data_count < 65535 )
        ping_data_count++;
}

void main(void)
{

// Initialize the device
SYSTEM_Initialize();
// If using interrupts in PIC18 High/Low Priority Mode you need to enable
// the Global High and Low Interrupts
// If using interrupts in PIC Mid-Range Compatibility Mode you need to
// enable the Global and Peripheral Interrupts
// Use the following macros to:
// Enable high priority global interrupts
//INTERRUPT_GlobalInterruptHighEnable();
// Enable low priority global interrupts.
//INTERRUPT_GlobalInterruptLowEnable();
// Disable high priority global interrupts
//INTERRUPT_GlobalInterruptHighDisable();
// Disable low priority global interrupts.
//INTERRUPT_GlobalInterruptLowDisable();
// Enable the Global Interrupts
INTERRUPT_GlobalInterruptEnable();
// Enable the Peripheral Interrupts
INTERRUPT_PeripheralInterruptEnable();
// Disable the Global Interrupts
//INTERRUPT_GlobalInterruptDisable();
// Disable the Peripheral Interrupts
//INTERRUPT_PeripheralInterruptDisable();
LORAWAN_Init(RxData, RxJoinResponse);
EUSART1_Initialize();
ECL_parser_init( &cmdline, &(top[0]) );
printf("lora start...\r\n");
printf("%s> ", ECL_get_prompt());

Lora_ECL_config_display(0,NULL,NULL);
        
ee_config_read(nwkskey_a);
ee_config_read(appskey_a);
ee_config_read(devaddr_a);

LORAWAN_SetNetworkSessionKey(ee_config.nwkskey);
LORAWAN_SetApplicationSessionKey(ee_config.appskey); 
LORAWAN_SetDeviceAddress(ee_config.devaddr);
LORAWAN_Join(ABP);


TMR0_SetInterruptHandler(timer_handle_for_ping_data);
TMR0_StartTimer();

//EUSART1_Write("Loar start\r\n");

//    printf("Loar start\r\n");
/*
LORAWAN_SetDeviceEui(DevEui);
LORAWAN_SetApplicationKey(AppKey);
LORAWAN_SetApplicationEui(AppEui);
LORAWAN_Join(OTAA);
*/
//freqUsed = LORAWAN_GetFrequency(4);
    
    while (1)
    {
        // Add your application code
        LORAWAN_Mainloop();
        // All other function calls of the user-defined
        // application must be made here
       
        if(sw_b != IO_RA2_GetValue())
        {
             __delay_ms(1);
             if(sw_b != IO_RA2_GetValue())
             {
                if(IO_RA2_GetValue() == 1)
                {
                    //while(IO_RA2_GetValue() == 0);
                    sw_count++;
                }
             sw_b = IO_RA2_GetValue();   
             } 
        }
        
        if(sw_count != sw_count_old)
	    {
             lora_send_data[0] = (sw_count>>24)&0xff;
             lora_send_data[1] = (sw_count>>16)&0xff;
             lora_send_data[2] = (sw_count>>8)&0xff;
             lora_send_data[3] =  sw_count&0xff;
             hexToChar(lora_send_data, send_string_buf, 4);
             LORAWAN_Send(CNF, 1, send_string_buf, 8);
             
             sw_count_old = sw_count;
             printf("new sw:%d\r\n", sw_count);
             continue;
        }   
        
        if(ping_data_count > 30) //3000)  //report every 5 minutes
        {
             lora_send_data[0] = (sw_count>>24)&0xff;
             lora_send_data[1] = (sw_count>>16)&0xff;
             lora_send_data[2] = (sw_count>>8)&0xff;
             lora_send_data[3] =  sw_count&0xff;
             hexToChar(lora_send_data, send_string_buf, 4);
             send_string_buf[8] = 'T';
             LORAWAN_Send(CNF, 1, send_string_buf, 9);
             
             ping_data_count = 0;
             printf("timer trigger:%d\r\n",sw_count);
        } 
        Cmd_Handle_Process();
    }
}



void hexToChar(uint8_t * value, uint8_t * str, int lens)  
{  
	//int sign = 0;
	int i=0;
	//int j; 
	//memset(str, 0, lens*2);
    uint8_t temp;
    
    for(i=0;i<lens;i++)
    {
        temp = value[i]/16;
        if(temp > 9)
           str[2*i] = 'A'+ (temp-10);
        else
           str[2*i] = '0'+ temp;
      
        temp = value[i]%16;
        if(temp > 9)
           str[2*i + 1] = 'A'+ (temp-10);
        else
           str[2*i + 1] = '0'+ temp;
    }
	
} 